def bin_to_hex_txt(input_path, output_path, bytes_per_line=16):
    with open(input_path, 'rb') as bin_file, open(output_path, 'w') as txt_file:
        count = 0
        while (byte := bin_file.read(1)):
            # 将字节转换为两位十六进制字符串
            hex_str = f'{int.from_bytes(byte, "big"):02X}'
            txt_file.write(hex_str + ' ')
            count += 1
            # 每读取指定数量的字节后换行
            if count % bytes_per_line == 0:
                txt_file.write('\n')
        # 如果最后一行未满，也添加换行符
        if count % bytes_per_line != 0:
            txt_file.write('\n')
if __name__ == '__main__':
    # 使用示例
    input_file = 'p.bin'    # 替换为您的二进制文件路径
    output_file = 'p.txt'    # 输出的文本文件路径
    bin_to_hex_txt(input_file, output_file, bytes_per_line=16)